package com.tzbank.wisdom.utils;


import org.apache.commons.io.output.ByteArrayOutputStream;


import com.tzbank.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import java.util.Date;
import java.util.HashMap;

import java.util.Map;
import java.util.UUID;
import sun.misc.BASE64Decoder;  


@SuppressWarnings("restriction")
@Slf4j
public class FileUploadUtil {
	
	
    public static Map<String, String> upload(String fileDate,String filePath){
    	//对字节数组字符串进行Base64解码并生成图片  
        BASE64Decoder decoder = new BASE64Decoder();  
        if(fileDate==null){//图像数据为空  
        	log.info("---------->图片Base64解码异常----->fileDate is empty");
        }
        String dateFileName=   DateUtils.dateToDateFullString(new Date());                   
        //获取文件的后缀名
        String suffix =".jpg";
    	String uuid = UUID.randomUUID().toString().replace("-", "").substring(10, 20);
        String ocrImgName= dateFileName+"-"+uuid+suffix;
        //String suffix = fileName+fileName.substring(fileName.lastIndexOf("."));       
        //String filePath = "/home/admin/img/"+type+"/";           
     	Map<String, String> param = new HashMap<String, String>();
        try{  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(fileDate);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }    
        File f = new File(filePath,ocrImgName);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }   
        String localFile =  filePath+ocrImgName;      
        OutputStream out = new FileOutputStream(localFile);      
        out.write(b);  
        out.flush();  
        out.close();         
    	param.put("localFile", localFile);
    	param.put("ocrImgName", ocrImgName);       
        }catch (Exception e) {  
   
            log.info("---------->图片Base64解码异常：----->"+e);
        }    
        log.info("---------->图片Base64解码，并保存成功----->success");
        return param;    	
    }
	

    

    /**
     * 获得指定文件的byte数组
     */

    public static byte[] getBytes(String filePath) throws Exception{
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        if(fis!=null){
            fis.close();
        }
        if(bos!=null){
            bos.close();
        }
        buffer = bos.toByteArray();
        return buffer;
    }
}
